package io.gitee.zhangbinhub.acp.cloud.helloworld.component

import io.gitee.zhangbinhub.acp.cloud.loadbalancer.AcpLoadBalancerAlgorithm
import org.noear.solon.annotation.Component
import org.noear.solon.cloud.model.Instance
import org.noear.solon.core.handle.Context
import java.util.*
import java.util.concurrent.ThreadLocalRandom

@Component
class CustomerLoadBalancerAlgorithm : AcpLoadBalancerAlgorithm {
    override fun getServiceId(): String = AcpLoadBalancerAlgorithm.DEFAULT_SERVICE_ID

    override fun getInstance(context: Context?, instances: MutableList<Instance>): Instance {
        println(">>>>>>>> CustomerLoadBalancerAlgorithm")
        val random = ThreadLocalRandom.current().nextDouble(0.0, 1.0)
        val sortedInstances = instances.sortedBy { it.weight() }
        val weights = sortedInstances.map { it.weight() }.toTypedArray()
        var index: Int = Arrays.binarySearch(weights, random)
        if (index < 0) {
            index = -index - 1
            return if (index < weights.size && random < weights[index]) {
                sortedInstances[index]
            } else if (weights.isEmpty()) {
                throw IllegalStateException("Cumulative Weight wrong , the array length is equal to 0.")
            } else {
                sortedInstances.last()
            }
        } else {
            return sortedInstances[index]
        }
    }
}
